/**
 * Created by Sever on 2016/11/21.
 */
var utils = require('utils');
var html2canvas = require('html2canvas');

const app = new Vue({
    //路由
    // router: router,
    //要挂载的dom元素
    el:'#app',
    //模板
    template:'',
    //数据
    data:{
        line1:{
            font_size:'20px',
            text:'丢雷',
        },
        line2:{
            font_size:'14px',
            text:'fire in the hold'
        },
        json_data:{},
    },
    beforeCreate: function () {
        utils.adaptive();
        console.log("生命周期-创建event实例前");


    },
    mounted: function () {
        var _this = this;
        console.log("生命周期-挂载到#app后");

        _this.init();

    },
    updated:function(){
        var _this = this;
        // console.log("生命周期-数据更新后");

        _this.init();
    },
    //各种方法
    methods: {
        init:function(){
            //1.将div转成canvas
            $("#output_img canvas").remove();
            html2canvas($("#input_div")[0]).then(function(canvas) {
                console.log(canvas.width);
                $("#output_img").append(canvas);


                //2. 图片导出为 png 格式
                var type = 'png';
                var imgData = canvas.toDataURL(type);

                /**
                 * 获取mimeType
                 * @param  {String} type the old mime-type
                 * @return the new mime-type
                 */
                var _fixType = function (type) {
                    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
                    var r = type.match(/png|jpeg|bmp|gif/)[0];
                    return 'image/' + r;
                };

                // 加工image data，替换mime type
                imgData = imgData.replace(_fixType(type), 'image/octet-stream');



                /**
                 * 在本地进行文件保存
                 * @param  {String} data     要保存到本地的图片数据
                 * @param  {String} filename 文件名
                 */
                var saveFile = function (data, filename) {
                    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
                    save_link.href = data;
                    save_link.download = filename;

                    var event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    save_link.dispatchEvent(event);
                };

                // 下载后的图片名
                var filename = 'img_' + (new Date()).getTime() + '.' + type;
                // download
                $("#download").click(function(){
                    saveFile(imgData, filename);
                });
            });




        }
    }
});
